import Vue from "vue";
import { appInfo } from "@/utils";
import Store from "@/store";

const callNativeWithPromise = (msg) => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromise",
        msg
    );
};

const callNative = (msg) => {
    return Vue.Native.callNative("AtlasModule", "execute", msg);
};

/**
 * 定位焦点
 * $refs：this.$refs.view 需要定位焦点标签的$refs对象
 * */
const requestFocus = ($refs) => {
    console.log("requestFocus...1");
    if (!$refs || Store.getData("rejectManualFocus")) return;
    console.log("requestFocus...2");
    Vue.Native.callUIFunction($refs, "requestFocus", [true]);
};

/**
 * 清空上一次记忆焦点
 * $refs：this.$refs.view ul的$refs对象
 * */
const clearFocusMemory = ($refs) => {
    Vue.Native.callUIFunction($refs, "clearFocusMemory");
};

/**
 * 预设焦点：适用于ul列表
 * $refs：this.$refs.view ul的$refs对象
 * index：第几个子标签
 * */
const setSelectChildPosition = ($refs, index) => {
    Vue.Native.callUIFunction($refs, "setSelectChildPosition", [index]);
};

/**
 * 设置后代元素的focusability：适用于div\ul
 * $refs：this.$refs.view ul的$refs对象
 * focusability
 *  0:FOCUS_BEFORE_DESCENDANTS
 *  1:FOCUS_AFTER_DESCENDANTS
 *  2:FOCUS_BLOCK_DESCENDANTS
 * */
const setDescendantFocusability = ($refs, focusability) => {
    if (!$refs) return;
    Vue.Native.callUIFunction($refs, "setDescendantFocusability", [
        focusability,
    ]);
};

// 设置元素本身焦点是否禁用
const setFocusable = ($refs, flag) => {
    if (!$refs) return;
    Vue.Native.callUIFunction($refs, "setFocusable", [flag]);
};

const loadImage = ($refs, url) => {
    console.log("loadImage", url);
    if (!$refs) return;
    Vue.Native.callUIFunction($refs, "loadImage", [url]);
};

/**
 * 通知 ListView 第几个子 item获得焦点。
 * $refs：this.$refs.view ul的$refs对象
 * index：第几个子标签
 * */
const requestChildFocus = ($refs, position) => {
    console.log("requestChildFocus...", $refs);
    console.log("requestChildFocus...", position);
    console.log("requestChildFocus...", $refs[position]);

    if (!$refs || Store.getData("rejectManualFocus")) return;
    Vue.Native.callUIFunction($refs, "requestChildFocus", [position]);
};

/**
 *  ListView 在没有焦点时，第几个item会优先获得焦点。
 * $refs：this.$refs.view ul的$refs对象
 * index：第几个子标签
 * */
const setTargetFocusChildPosition = ($refs, position) => {
    Vue.Native.callUIFunction($refs, "setTargetFocusChildPosition", [position]);
};

/**
 *  ListView 设置初始化相关信息
 * $refs：this.$refs.view ul的$refs对象
 * @param {Object} params
 * {position:number ,requestFocus:boolen ,target:String(name),oneShot:boolen ,blockOthers:boolen ,delay:int}
 *
 * */
const setInitPosition = ($refs, params) => {
    Vue.Native.callUIFunction($refs, "setInitPosition", [params]);
};

// 暂存焦点
const saveFocus = ($refs, focusId) => {
    Vue.Native.callUIFunction($refs, "saveFocus", [focusId]);
};

// setTempFocus 和 monitorLayout 配和使用
// 挂起焦点，将焦点挂载到临时元素
const setTempFocus = ($refs) => {
    Vue.Native.callUIFunction($refs, "setTempFocus");
};

// 监听焦点挂起的列表渲染回调
const monitorLayout = ($refs, focusId) => {
    Vue.Native.callUIFunction($refs, "monitorLayout", [focusId]);
};

/**
 * 获取设备信息
 * getDeviceInfo().then(res => {})
 * */
const getDeviceInfo = () => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromise",
        { action: "_A_GET_DEVICE_INFO_" }
    );
};

/**
 * 获取嵌入到瀑布流的fragment可见性
 * pageShown: -1 非法，不要使用这个结果,  0 不可见,  1 可见
 * getPageShown().then(res => {})
 * */
const getPageShown = () => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromise",
        { action: "_A_GET_PAGE_SHOWN_" }
    );
};

/**
 * 获取设备信息
 * fetchDataInfo().then(res => {})
 * */
const fetchDataInfo = (type, key, val) => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromiseByFetch",
        { type, key, val }
    );
};

/**
 * 批量获取bims信息
 * keyArray bims的key数组
 * batchFetchBimsInfo(keyArray).then(res => {})
 */
const batchFetchBimsInfo = (keyArray) => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromiseByBatchFetch",
        keyArray
    );
};

/**
 *
 * @param {*} $refs
 * @param {*} visibility gone 隐藏不占空间 visible 正常显示 invisible 隐藏占空间
 */
const setVisibility = ($refs, visibility) => {
    Vue.Native.callUIFunction($refs, "setVisibility", [visibility]);
};
/**
 * 做抖动动画
 * @param {*} $refs
 * @param {*} position 0 横向抖动（默认）1 竖向抖动
 */
const doShakeAnimation = ($refs, position) => {
    Vue.Native.callUIFunction($refs, "doShakeAnimation", [position]);
};

/**
 * 系统TOAST提示（各品牌电视的提示样式不同，介意的可自己做）
 * msg：提示文字
 * long: 显示时间长短，true为7秒，false为4秒，默认false
 * */
const TOAST = (msg, long) => {
    long = long || false;
    Vue.Native.callNative("AtlasModule", "Toast", { text: msg, long });
};

/**
 * 应用内打开新应用页面
 * url：页面路由
 * query：页面参数
 * clearTask：是否关闭其他页面，可用于返回首页
 * background: 新页面背景色例如 #000000
 * */
const newPage = (url, query, background, clearTask) => {
    clearTask = clearTask || false;
    background = background || "#000000";
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_A_NEW_PAGE_",
        packageName: appInfo.packageName,
        entryPage: JSON.stringify({ url, query }),
        background,
        clearTask: clearTask,
    });
};

/**
 * 应用内打开新页面
 * url：页面路由
 * query：页面参数
 * max：最多数量
 * background: 新页面背景色例如 #000000
 * */
const newPageMax = (url, query, num, background) => {
    background = background || "#000000";
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_A_NEW_PAGE_",
        packageName: appInfo.packageName,
        entryPage: JSON.stringify({ url, query }),
        background,
        flag: route,
        max: num,
    });
};

/**
 * 打开新的快应用
 * zipUrl: 资源zip包下载地址
 * params：启动参数 {url:'', query:''}
 * background: 新页面背景色例如 #000000
 * packageName：应用包名
 * */
const newApp = (zipUrl, params, background, packageName) => {
    background = background || "#000000";
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_A_NEW_PAGE_",
        url: zipUrl,
        entryPage: params,
        background,
        packageName,
    });
};

/**
 * 同一个应用内跳转不同的路由
 * url：页面路由
 * query：页面参数
 * */
const forward = (url, query) => {
    console.log("zsssf go forward 2");
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_A_FORWARD_",
        packageName: appInfo.packageName,
        entryPage: JSON.stringify({ url, query }),
    });
};

/**
 * 同一个应用内返回处理
 * */
const backPress = () => {
    Vue.Native.callNative("AtlasModule", "execute", { action: "_A_BACK_" });
};

/**
 * 打开通用跳转
 * data：{}
 * */
const goCommonJump = (data) => {
    const _url = JSON.stringify(data);
    const _url1 = appInfo.jump + encodeURIComponent(_url) + "||||";
    openGefo(_url1);
};
/**
 * 打开gefo
 * url 地址
 * */
const openGefo = (url) => {
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_A_OPEN_GEFO_",
        url,
    });
};

/**
 * 关闭当前页面
 * */
const closePage = () => {
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_A_CLOSE_PAGE_",
    });
};

/**
 * 埋点
 * name: 事件名称
 * data: 事件参数
 * */
const eventTrack = (name, data) => {
    Vue.Native.callNative("AtlasModule", "eventTrack", { name, data });
};

/**
 * localStorage.getItem 扩展
 * key:  key键
 * ystStamp: 数据结果校验stamp
 * */
const getItem = (key, ystStamp) => {
    return Hippy.bridge
        .callNativeWithPromise("StorageModule", "multiGet", [key])
        .then((r) => {
            if (!r || !r[0] || !r[0][1]) {
                return null;
            }

            let v = {};
            v.ystStamp = ystStamp;
            v.data = JSON.parse(r[0][1]);
            return JSON.stringify(v);
        })
        .catch((err) => convertErrors(err));
};

/**
 * localStorage.multiSet 扩展
 * arr:  arr数组
 * */
const multiSet = (arr) => {
    return Hippy.bridge
        .callNativeWithPromise("StorageModule", "multiSet", arr)
        .then((r) => {
            return r;
        })
        .catch((err) => convertErrors(err));
};

/**
 * localStorage.multiGet 扩展
 * keys:  key键数组
 * ystStamp: 数据结果校验stamp
 * */
const multiGet = (keys, ystStamp) => {
    return Hippy.bridge
        .callNativeWithPromise("StorageModule", "multiGet", keys)
        .then((r) => {
            let v = {};
            if (ystStamp) v.ystStamp = ystStamp;
            v.data = r;
            return v;
        })
        .catch((err) => convertErrors(err));
};

/**
 * localStorage.multiRemove 扩展
 * arr:  arr数组
 * */
const multiRemove = (arr) => {
    return Hippy.bridge
        .callNativeWithPromise("StorageModule", "multiRemove", arr)
        .then((r) => {
            return r;
        })
        .catch((err) => convertErrors(err));
};

/**
 * localStorage.multiGet 扩展
 * keys:  key键数组
 * ystStamp: 数据结果校验stamp
 * */
const multiGetAllKeys = () => {
    return Hippy.bridge
        .callNativeWithPromise("StorageModule", "getAllKeys")
        .then((r) => {
            // let v = {};
            // if(ystStamp)v.ystStamp = ystStamp;
            // v.data = r;
            return r;
        })
        .catch((err) => convertErrors(err));
};

/**
 * 模糊查询数据库所有符合条件的key值
 * localStorage.multiGet 扩展
 * value:  value键String
 * */
const multiGetKeysContains = (value) => {
    return Hippy.bridge
        .callNativeWithPromise("StorageModule", "getKeysContains", value)
        .then((r) => {
            return r;
        })
        .catch((err) => convertErrors(err));
};

/**
 * localStorage.multiGet 扩展
 * keys:  key键数组
 * ystStamp: 数据结果校验stamp
 * */
const getAllKeysData = (keys) => {
    return Vue.Native.callNativeWithPromise("AtlasModule", "multiGet", keys);
};

/**
 * getFullPath 获取完整assets路径
 * path:  相对路径，比如 "assets/raw/f_1.png" 等
 * getFullPath(path).then(res => {})
 * */
const getFullPath = (path) => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromise",
        { action: "_A_GET_FULL_PATH_", path }
    );
};

/**
 * notifyMount 通过引擎mount成功
 */
const notifyMount = () => {
    console.log("zsssf", "notifyMount 11");
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_CALL_LIFECYCLE_",
    });
    console.log("zsssf", "notifyMount 22");
};

/**
 * readLocalFile 读取本地文件
 * path:  相对路径，比如 "assets/raw/f_1.png" 等
 * readLocalFile(path).then(res => {})
 * */
const readLocalFile = (path) => {
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "executeWithPromise",
        { action: "_A_READ_LOCAL_FILE_", path }
    );
};

/**
 *
 * action值为enterFullScreen 进入全屏 或 exitFullScreen 退出全屏 或 focusNavTab 焦点移到launcher的 tab 或 switchFlow 切换flow
 * */
const lottieLoadAll = (urlArr) => {
    console.log("lottieLoadAll--", urlArr);
    return Vue.Native.callNativeWithPromise(
        "AtlasModule",
        "lottieLoadAll",
        urlArr
    );
};

/**
 *
 * action值为enterFullScreen 进入全屏 或 exitFullScreen 退出全屏 或 focusNavTab 焦点移到launcher的 tab 或 switchFlow 切换flow
 * */
const lottieLoad = (url) => {
    console.log("lottieLoad--", url);
    return Vue.Native.callNativeWithPromise("AtlasModule", "lottieLoad", url);
};

/**
 *
 * action值为enterFullScreen 进入全屏 或 exitFullScreen 退出全屏 或 focusNavTab 焦点移到launcher的 tab 或 switchFlow 切换flow
 * */
const onLauncherCall = (action, value) => {
    value = value || "";
    console.log("onLauncherCall--", action, value);
    return Vue.Native.callNativeWithPromise("AtlasModule", "onLauncherCall", {
        action,
        value,
    });
};

const onLauncherOpenApp = (data) => {
    console.log("onLauncherOpenApp--data", JSON.stringify(data));
    return Vue.Native.callNativeWithPromise("AtlasModule", "openApp", data);
};

/**
 *
 * @param {*} $refs $refs对象
 * @param {*} msid 标识，用于接收动画完成回调时判断是哪个控件做的动画
 * @param {*} aniList 动画列表
 */
const doAnimation = ($refs, msid, aniList) => {
    Vue.Native.callUIFunction($refs, "animation", [msid, aniList]);
};

/**
 * 暂停动画
 * @param {*} $refs $refs对象
 */
const pauseAnimation = ($refs) => {
    Vue.Native.callUIFunction($refs, "animationPause");
};

/**
 * 继续动画
 * @param {*} $refs $refs对象
 */
const resumeAnimation = ($refs) => {
    Vue.Native.callUIFunction($refs, "animationResume");
};

/**
 * 取消动画
 * @param {*} $refs $refs对象
 */
const cancelAnimation = ($refs) => {
    Vue.Native.callUIFunction($refs, "animationCancel");
};

/**
 * 127上报
 *
 * */
const reportE = (action, msg) => {
    Vue.Native.callNativeWithPromise("AtlasModule", "report", {
        level: "e",
        action,
        msg,
    });
};
const reportI = (action, msg) => {
    Vue.Native.callNativeWithPromise("AtlasModule", "report", {
        level: "i",
        action,
        msg,
    });
};
const reportW = (action, msg) => {
    Vue.Native.callNativeWithPromise("AtlasModule", "report", {
        level: "w",
        action,
        msg,
    });
};
const reportC = (msg) => {
    Vue.Native.callNativeWithPromise("AtlasModule", "report", {
        level: "c",
        action,
        msg,
    });
};
/**
 * 神策上报
 *
 * */
const reportSensors = (msg) => {
    Vue.Native.callNativeWithPromise("AtlasModule", "reportSensors", msg);
};

/**
 * 设置是否可以拖动seekbar：适用于seekbar
 * $refs：this.$refs.view seekbar的$refs对象
 * enable：true 表示可以拖动，false 标识禁止拖动
 * */
const setSeekEnable = ($refs, enable) => {
    console.log("setSeekEnable", enable);
    Vue.Native.callUIFunction($refs, "setSeekEnable", [enable]);
};

// text-view组件开启跑马灯效果
const startMarquee = (ref) => {
    Vue.Native.callUIFunction(ref?.$el, "startMarquee", [true]);
};

// marquee组件开启跑马灯效果
const resumeMarquee = (ref) => {
    Vue.Native.callUIFunction(ref?.$el, "resume", [true]);
};

// 已完成加载页面，告诉插件取消插件loading
const completeLoad = () => {
    Vue.Native.callNative("AtlasModule", "execute", {
        action: "_CALL_LOADCOMPLETE_",
    });
    console.log("_CALL_LOADCOMPLETE_====");
};

// 注册mqtt消息拦截器
const setMqttMsgFilter = (data) => {
    Vue.Native.callNative("AtlasModule", "setMqttMsgFilter", data);
};
 
// 注册mqtt反馈消息
const sendMqttMsg = (data) => {
    Vue.Native.callNative("AtlasModule", "sendMqttMsg", data);
};

// 注销mqtt消息拦截器
const clearMqttMsgFilter = ()=>{
  Vue.Native.callNative("AtlasModule", "clearMqttMsgFilter");
}

// 语音搜素消息拦截器
const setGlobalVoiceFilter = (data) => {
    Vue.Native.callNative("AtlasModule", "setGlobalVoiceFilter", data);
};

// 注销语音搜素消息拦截器
const clearGlobalVoiceFilter = () => {
    Vue.Native.callNative("AtlasModule", "clearGlobalVoiceFilter");
};

// 拉起jarvis对话apk
const sendBroadcast = (keys) => {
    console.log("sendBroadcast:msgList", JSON.stringify(keys));
    Vue.Native.callNative('AtlasModule', 'sendBroadcast', 'com.iflytek.xiri.action.userText', 'tv.icntv.ott', keys);
};

export default {
    callNativeWithPromise,
    callNative,
    requestFocus,
    clearFocusMemory,
    requestChildFocus,
    setTargetFocusChildPosition,
    setSelectChildPosition,
    setDescendantFocusability,
    setInitPosition,
    getDeviceInfo,
    fetchDataInfo,
    TOAST,
    newPage,
    newPageMax,
    newApp,
    goCommonJump,
    openGefo,
    closePage,
    forward,
    backPress,
    eventTrack,
    getItem,
    multiSet,
    multiGet,
    multiRemove,
    multiGetAllKeys,
    multiGetKeysContains,
    getAllKeysData,
    getFullPath,
    readLocalFile,
    reportE,
    reportI,
    reportW,
    reportC,
    reportSensors,
    lottieLoadAll,
    lottieLoad,
    onLauncherCall,
    onLauncherOpenApp,
    setFocusable,
    loadImage,
    doShakeAnimation,
    setVisibility,
    doAnimation,
    pauseAnimation,
    resumeAnimation,
    cancelAnimation,
    notifyMount,
    getPageShown,
    batchFetchBimsInfo,
    saveFocus,
    setTempFocus,
    monitorLayout,
    setSeekEnable,
    startMarquee,
    resumeMarquee,
    completeLoad,
    setMqttMsgFilter,
    sendMqttMsg,
    clearMqttMsgFilter,
    setGlobalVoiceFilter,
    clearGlobalVoiceFilter,
    sendBroadcast
};
